import {useCallback, useEffect, useMemo, useState} from 'react';
import {useForm} from 'react-hook-form';
import {useFocusEffect} from '@react-navigation/native';
import {getDeptList, getSealList, sealCreate, sealUpdate} from '../../../api/seal';
import {UserApi} from '../../../api/user';
import {ToastAndroid} from 'react-native';
import {SealItem} from "../../../types/api";

// 定义表单数据类型，这应该与组件中的类型一致
export type SealFormData = {
    materialName: string;
    materialType: string;
    applyDept: number;
    applyTitle: string;
    attention: string;
    attachments: {
        name?: string;
        url: string;
        size?: string;
    }[];
    sealTypes: { id: number; name: string; quantity: number }[];
    phone: string;
    unit: string; // 这是用户选择的单位名称
    startUserSelectAssignees: {
        handler: { name: string; signed: boolean };
        reviewer: { name: string; signed: boolean };
        unitHead: { id: number[]; name: string; signed: boolean };
    };
};

/**
 * @钩子 useCreateSealForm
 * @功能描述 封装创建印章申请表单的所有逻辑，包括：
 *   - 表单状态管理 (react-hook-form)
 *   - 数据获取 (单位列表、用户信息)
 *   - 派生状态计算 (印章选项)
 *   - 表单提交逻辑
 */
export function useCreateSealForm(type: string, info: any) {
    // --- 状态管理 ---
    const [sealData, setSealData] = useState<SealItem[]>([]);
    const [units, setUnits] = useState<any[]>([]);
    const [departments, setDepartments] = useState<{ id: number; name: string }[]>([]);
    const [userInfo, setUserInfo] = useState<any>();

    // --- 表单管理 ---
    const form = useForm<SealFormData>({
        defaultValues: {
            materialName: info?.materialName || "",
            materialType: info?.materialType || "1",
            attention: info?.attention || '',
            attachments: [{}],
            unit: info?.applyTitle?.replace(/\s/g, '').match(/^([\u4e00-\u9fa5]+)印章申请单/)[1] ?? '',
            sealTypes: info?.sealTypes || [],
            phone: info?.phone || '',
            startUserSelectAssignees: {
                handler: {
                    name: info?.signers.split("，")[0] || '',
                    signed: false
                },
                reviewer: {
                    name: info?.signers.split("，")[1] || '',
                    signed: false
                },
                unitHead: {
                    id: [],
                    name: '',
                    signed: false
                },
            },
        },
    });

    // --- 数据获取 ---
    const init = useCallback(async () => {
        try {
            // 1. 获取单位列表
            const res = await getDeptList();
            if (res && res.code === 0 && Array.isArray(res.data)) {
                // 将后端的数据结构转换为正常结构: {id, name}[]
                const departmentList =
                    res.data.map((item: { [key: string]: number }) => {
                        const name = Object.keys(item)[0];
                        const id = item[name];
                        return {id, name};
                    });
                console.log(departmentList)
                setUnits(departmentList.map(dept => {
                    return {
                        label: dept.name,
                        value: dept.name
                    }
                }));
                setDepartments(departmentList);
                // 清空印章数据，因为初始时没有单位被选中
                setSealData([]);
            } else {
                console.warn('获取单位列表失败:', res);
                setUnits([]);
                setDepartments([]);
            }

            // 2. 获取用户信息
            const userRes = await UserApi.getCurrentUser();
            setUserInfo(userRes?.data);

        } catch (error) {
            console.error('初始化数据失败:', error);
        }
    }, []);

    useFocusEffect(
        useCallback(() => {
            init();
            form.reset();
            if (info) {
                form.reset(form.getValues())
            }
        }, [init, form.reset])
    );

    // --- 逻辑与副作用 ---
    const selectedUnit = form.watch('unit');

    useEffect(() => {
        const fetchSeals = async () => {
            if (selectedUnit) {
                const selectedDepartment = departments.find(d => d.name === selectedUnit);
                if (selectedDepartment) {
                    try {
                        const res = await getSealList({orgId: selectedDepartment.id});
                        if (res.code === 0 && res.data.list) {
                            console.log(res.data.list.map(item => {
                                return {
                                    label: item.sealName,
                                    value: {
                                        id: item.id,
                                        name: item.sealName
                                    },
                                }
                            }))
                            setSealData(res.data.list);
                        } else {
                            setSealData([]); // 清空旧数据
                        }
                    } catch (error) {
                        console.error('Failed to fetch seals:', error);
                        setSealData([]); // 出错时也清空
                    }
                } else {
                    setSealData([]);
                }
            } else {
                setSealData([]);
            }
        };
        fetchSeals();
    }, [selectedUnit, departments]);

    const sealOptions = useMemo(() => {
        if (!selectedUnit) {
            return [];
        }
        return sealData.map(item => ({
            label: item.sealName,
            value: {
                id: item.id,
                name: item.sealName
            },
        }));
    }, [selectedUnit, sealData]);

    // --- 表单提交 ---
    const onSubmit = useCallback(async (raw: SealFormData, files: {
        url: string,
        name: string,
        size: number
    }[] = []) => {
        const selectedDept = departments.find(dept => dept.name === raw.unit);
        if (!selectedDept) {
            ToastAndroid.show(`错误：找不到单位“${raw.unit}”`, ToastAndroid.LONG);
            return;
        }
        const data = {
            ...raw,
            applyDept: selectedDept.id,
            applyTitle: `${raw.unit} 印章申请单`,
            startUserSelectAssignees: {...raw.startUserSelectAssignees, signers: ""},
            attachments: files,
            id: info?.id || '',
            signers: type === "update" ? `${raw.startUserSelectAssignees.handler.name}，${raw.startUserSelectAssignees.reviewer.name}，${raw.startUserSelectAssignees.unitHead.name}` : ""
        };
        console.log(data);
        let res;
        if (type === "create") {
            res = await sealCreate(data);
        } else {
            res = await sealUpdate(data);
        }

        if (res.code === 0) {
            ToastAndroid.show('提交成功！', ToastAndroid.SHORT);
            return true;
        } else {
            ToastAndroid.show(`提交失败: ${res.msg}`, ToastAndroid.SHORT);
            return false;
        }
    }, [departments, sealCreate, type]);

    return {
        form,
        states: {
            units,
            sealOptions,
            userInfo,
            isSubmitting: form.formState.isSubmitting,
        },
        handlers: {
            onSubmit,
        },
    };
}
